package com.inspur.dgov.vlbod.secure.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.inspur.dgov.vlbod.http.DgovResponse;
import com.inspur.dgov.vlbod.secure.constant.SecureConstant;
import com.inspur.dgov.vlbod.secure.token.TokenFactory;
import com.inspur.dgov.vlbod.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * jwt拦截器校验
 *
 * @Author chiyupei
 * @Date 19/6/27 下午4:22
 * @Version 1.0
 * @Description jwt拦截器校验
 */
@Slf4j
public class SecureInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${dgov.auth.disable:false}")
    private Boolean disableAuth;

    @Override
    @Deprecated
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //如果禁用安全认证，则直接返回
        if(disableAuth){
            return true;
        }
        String authorization = request.getHeader(SecureConstant.BASIC_HEADER_KEY);
        if (StrUtil.isEmpty(authorization)) {
            authorization = request.getParameter(SecureConstant.BASIC_TOKEN_KEY);
        }
        if (null != authorization) {
            boolean authorizationExist = this.redisTemplate.hasKey(SecureConstant.TOKEN_USER_KEY + authorization);
            if (authorizationExist) {
                return true;
            }
        }
        log.warn("签名认证失败，请求接口：{}，请求IP：{}，请求参数：{}", request.getRequestURI(), WebUtil.getIP(request), JSONUtil.toJsonStr(request.getParameterMap()));
        DgovResponse result = DgovResponse.fail("请求未授权", HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpServletResponse.SC_OK);
        try {
            response.getWriter().write(Objects.requireNonNull(JSONUtil.toJsonStr(result)));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
        return false;
    }
}
